﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;
using System.Web.Mvc;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using MovieAPI.Models;
using Newtonsoft.Json.Linq;

namespace MovieAPI.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*"), RequireHttpsAttribute]
    public class UserController : ApiController
    {
        private filmEntities db = new filmEntities();

        // GET: api/User
        public IQueryable<UserInfo> GetUserInfo()
        {
            return db.UserInfo;
        }

        // GET: api/User/5
        [ResponseType(typeof(UserInfo))]
        public IHttpActionResult GetUserInfo(int id)
        {
            UserInfo userInfo = db.UserInfo.Find(id);
            if (userInfo == null)
            {
                return NotFound();
            }

            return Ok(userInfo);
        }

        // PUT: api/User/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutUserInfo(int id, UserInfo userInfo)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != userInfo.UserID)
            {
                return BadRequest();
            }

            db.Entry(userInfo).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserInfoExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/User
        [ResponseType(typeof(UserInfo))]
        public IHttpActionResult PostUserInfo(UserInfo userInfo)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.UserInfo.Add(userInfo);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = userInfo.UserID }, userInfo);
        }

        // DELETE: api/User/5
        [ResponseType(typeof(UserInfo))]
        public IHttpActionResult DeleteUserInfo(int id)
        {
            UserInfo userInfo = db.UserInfo.Find(id);
            if (userInfo == null)
            {
                return NotFound();
            }

            db.UserInfo.Remove(userInfo);
            db.SaveChanges();

            return Ok(userInfo);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool UserInfoExists(int id)
        {
            return db.UserInfo.Count(e => e.UserID == id) > 0;
        }
        [System.Web.Http.HttpGet]
        /// <summary>
        /// 通过用户名登录
        /// </summary>
        /// <param name="LoginName"></param>
        /// <param name="LoginPwd"></param>
        /// <returns></returns>
        /// 
        public IHttpActionResult LoginbyUserName(string LoginName, string LoginPwd)
        {
            if (db.UserInfo.Where(u => u.UserAccount == LoginName).Count() > 0)
            {
                UserInfo user = db.UserInfo.FirstOrDefault(u => u.UserAccount == LoginName);
                if (user.UserPwd == LoginPwd)
                {
                    return Ok(user);
                }
                //-1代表密码错误
                return Ok(-1);
            }
            //-2代表没有这个用户
            return Ok(-2);
        }
        [System.Web.Http.HttpGet]
        public IHttpActionResult SelectUser(int ID) 
        {
            return Ok(db.UserInfo.Where(u => u.UserID == ID).FirstOrDefault());
        }
        /// <summary>
        /// 通过手机验证码登录
        /// </summary>
        /// <param name="Phone"></param>
        /// <returns></returns>
        public IHttpActionResult LoginByPhone(string Phone)
        {
            if (db.UserInfo.Where(u => u.PhoneNum == Phone).Count() > 1)
            {
                UserInfo user = db.UserInfo.FirstOrDefault(u => u.PhoneNum == Phone);
                return Ok(user);
            }
            //-2代表没有这个用户
            return Ok(-2);
        }
        public IHttpActionResult GetMa(string PhoneNum)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAI4G166dPGwX2ZYFrDfSLJ", "oRs4xsUhBgZ4vXL8aTeOhCeFQmD0YO");
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";

            string MA = "";
            Random rNum = new Random();//随机生成类
            int num1 = rNum.Next(0, 9);//返回指定范围内的随机数
            int num2 = rNum.Next(0, 9);
            int num3 = rNum.Next(0, 9);
            int num4 = rNum.Next(0, 9);
            int num5 = rNum.Next(0, 9);
            int[] nums = new int[5] { num1, num2, num3, num4, num5 };
            for (int i = 0; i < nums.Length; i++)//循环添加五个随机生成数
            {
                MA += nums[i].ToString();
            }
            request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumbers", PhoneNum);
            request.AddQueryParameters("SignName", "Moive影悦");
            request.AddQueryParameters("TemplateCode", "SMS_192825758");
            request.AddQueryParameters("TemplateParam", "{\"code\":\"" + MA + "\"}");
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                System.Text.Encoding.Default.GetString(response.HttpResponse.Content);
                return Ok(MA);
            }
            catch (ServerException e)
            {
                return Ok(e.ToString());
            }
            catch (ClientException e)
            {
                return Ok(e.ToString());
            }

        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public IHttpActionResult AddUser([FromBody] dynamic data)
        {
            UserInfo userInfo = new UserInfo();
            JObject obj = JObject.Parse(data.ToString());
            if (!string.IsNullOrEmpty(obj["data"]["UserName"].Value<string>()))
            {
                userInfo.UserName = obj["data"]["UserName"].Value<string>();
            }
            
            if (!string.IsNullOrEmpty(obj["data"]["UserAccount"].Value<string>()))
            {
                userInfo.UserAccount =obj["data"]["UserAccount"].Value<string>();
            }
            
            if (!string.IsNullOrEmpty(obj["data"]["UserPwd"].Value<string>()))
            {
                userInfo.UserPwd = obj["data"]["UserPwd"].Value<string>();
            }
            if (!string.IsNullOrEmpty(obj["data"]["PhoneNum"].Value<string>()))
            {
                userInfo.PhoneNum = obj["data"]["PhoneNum"].Value<string>();
            }
            userInfo.Sex = true;
            userInfo.UserTx = "3ea6beec64369c2642b92c6726f1epng.png";
            if (db.UserInfo.Where(u=>u.UserAccount==userInfo.UserAccount).Count()>0)
            {
                return Ok(3);
            }
            db.UserInfo.Add(userInfo);

            if (db.SaveChanges() > 0)
            {
                return Ok(1);
            }
            else {
                return Ok(2);
            }
        }

        [System.Web.Http.HttpGet]
        public IHttpActionResult GetSex() {
            using (filmEntities db = new filmEntities())
            {
                var Money = db.UserInfo.GroupBy(O => new { ID = O.Sex }).Select(O => new { Sex =(bool)O.Key.ID?"男":"女", Total = O.Count() }).ToList();
                

                var objDim = new List<Tuple<string, int>>();
                for (int i = 0; i < Money.Count(); i++)
                {
                    objDim.Add(new Tuple<string, int>(Money[i].Sex, Money[i].Total));
                }
                return Ok(objDim);
            }
            
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public IHttpActionResult UpdateUser([FromBody] dynamic data)
        {
            UserInfo userInfo = new UserInfo();
            JObject obj = JObject.Parse(data.ToString());
            if (!string.IsNullOrEmpty(obj["data"]["UserName"].Value<string>()))
            {
                userInfo.UserName = obj["data"]["UserName"].Value<string>();
            }

            if (!string.IsNullOrEmpty(obj["data"]["UserAccount"].Value<string>()))
            {
                userInfo.UserAccount = obj["data"]["UserAccount"].Value<string>();
            }

            if (!string.IsNullOrEmpty(obj["data"]["UserPwd"].Value<string>()))
            {
                userInfo.UserPwd = obj["data"]["UserPwd"].Value<string>();
            }
            if (!string.IsNullOrEmpty(obj["data"]["PhoneNum"].Value<string>()))
            {
                userInfo.PhoneNum = obj["data"]["PhoneNum"].Value<string>();
            }
            if (!string.IsNullOrEmpty(obj["data"]["UserID"].Value<string>()))
            {
                userInfo.UserID = int.Parse(obj["data"]["UserID"].Value<string>());
            }
            if (!string.IsNullOrEmpty(obj["data"]["UserSex"].Value<string>()))
            {
                userInfo.Sex = obj["data"]["UserSex"].Value<string>()=="1" ? true : false;
            }
            if (!string.IsNullOrEmpty(obj["data"]["UserAddress"].Value<string>()))
            {
                userInfo.UserAddress = obj["data"]["UserAddress"].Value<string>();
            }
            if (!string.IsNullOrEmpty(obj["data"]["UserTx"].Value<string>()))
            {
                userInfo.UserTx = obj["data"]["UserTx"].Value<string>();
            }
            if (!string.IsNullOrEmpty(obj["data"]["UserBirthDay"].Value<string>()))
            {
                userInfo.UserBirth =DateTime.Parse(obj["data"]["UserBirthDay"].Value<DateTime>().ToShortDateString());
            }
            db.Entry(userInfo).State = EntityState.Modified;
            if (db.SaveChanges() > 0)
            {
                return Ok(1);
            }
            else
            {
                return Ok(2);
            }
        }
        
    }
}